var mongoose = require('../mongoose.js').mongoose;
var SchemaCrop = require('./schemaCrop.js').SchemaCrop;
var Crop = require('./schemaCrop.js').Crop;
var SchemaBuilding = require('./schemaBuilding.js').SchemaBuilding;
var Building = require('./schemaBuilding.js').Building;

var gv = require('../globalVars.js').gv;

var SchemaHero = mongoose.Schema({
        name    :   { type : String,    required : true,    unique : true, trim : true },
        gold    :   { type: Number,     default: gv.playerStartGold },
        level   :   { type: Number,     default: gv.playerLevel },
        health  :   { type: Number,     default: gv.playerHealth },
        maxHealth : { type: Number,     default: gv.playerHealth },
        pos     :   {
            row :   Number,
            col :   Number
        },
    //TODO implement connected or not
        connected: Boolean,
        tiles : [],
        crops   :   [],
        buildings : []
    }, { versionKey: false });

SchemaHero.methods.setPosition = function(row, col){
    this.pos.row = row;
    this.pos.col = col;
}

function getHeroById(id, callback) {
    Hero.findById(id, function(err, hero) {
        if(err) console.log('--- getHeroById err : '+err.message);
        else callback(hero);
    });
}

function getHeroByName(hName, callback) {
    Hero.findOne({name : hName}, function(err, hero) {
        if(err) console.log(err.message);
        else callback(hero);
    })
}

function getAllHeros(callback) {
    Hero.find(function(err, heros) {
        if(err) console.log(err.message);
        else callback(heros);
    })
}

function updHero(hero, newHero) {
    hero.tiles = newHero.tiles;
    hero.crops = newHero.crops;
    hero.buildings = newHero.buildings;

    hero.gold = newHero.gold;
    hero.level = newHero.level;
    hero.health = newHero.health;
    hero.maxHealth = newHero.maxHealth;

    hero.save(function(err) {
        if(err) console.log('--- updHero err : '+err.message);
        else console.log('--- updHero OK');
    });
}

var Hero = mongoose.model('Hero', SchemaHero);

exports.SchemaHero = SchemaHero;
exports.Hero = Hero;
exports.getHeroById = getHeroById;
exports.getHeroByName = getHeroByName;
exports.getAllHeros = getAllHeros;
exports.updHero = updHero;